package cn.edu.cuit.elena.web.service;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.cuit.elena.trace.Tracer;
import cn.edu.cuit.elena.transaction.system.UserContext;
import cn.edu.cuit.elena.transaction.system.priviledge.PriviledgeManager;

public class SecurityFilter
    implements Filter
{

    public void destroy()
    {
        //Do Nothing
    }

    public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException,
        ServletException
    {
        int index = ( (HttpServletRequest) request ).getRequestURL().toString()
            .indexOf( ( (HttpServletRequest) request ).getContextPath() )
            + ( (HttpServletRequest) request ).getContextPath().length();
        String url = ( (HttpServletRequest) request ).getRequestURL().toString().substring( index );
        UserContext userContext = (UserContext) ( (HttpServletRequest) request ).getSession().getAttribute(
            ServiceServlet.ServiceConstants.USERCONTEXT.mark() );

        //URLHelper.toQualifiedPath();

        if( PriviledgeManager.accessLegal( userContext, url ) )
        {
            chain.doFilter( request, response );

            Tracer.infoTrace( this.getClass(), "Filter url : " + url + ", User : " + userContext.getUserName(), null );
        }
        else
        {
            //request.getRequestDispatcher( ServiceServlet.ServiceConstants.ILLEGAL_ACCESS.mark() ).forward( request, response );
            ( (HttpServletResponse) response ).sendRedirect( ( (HttpServletRequest) request ).getContextPath()
                + ServiceServlet.ServiceConstants.ILLEGAL_ACCESS.mark() );
            if( userContext == null )
            {
                Tracer.infoTrace( this.getClass(), "Filter redirects to  : "
                    + ServiceServlet.ServiceConstants.ILLEGAL_ACCESS.mark() + ", due to UserContext is null", null );
            }
            else
            {
                Tracer.infoTrace( this.getClass(), "Filter redirects to  : "
                    + ServiceServlet.ServiceConstants.ILLEGAL_ACCESS.mark() + ", User : " + userContext.getUserName(),
                    null );
            }
        }
    }

    public void init( FilterConfig arg0 ) throws ServletException
    {
        // Do nothing
    }

}
